from django.shortcuts import render

# Create your views here.
from rest_framework.viewsets import ModelViewSet
from .models import Brand
from .serializer import BrandSer
#品牌视图集
class BrandViewSet(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

#上传图片
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings
import os
class UploadLogoAPIView(APIView):
    #前端el-upload 自己发送的post请求
    def post(self,request):
        #获取上传的数据
        file = request.FILES.get('file')
        print("前端上传的文件：",file,type(file))
        #file 身上有两个属性需要使用
        #file.file 当前的文件字节流 BytesIO
        #file.name 当前的文件的名字

        #将文件字节流写入服务器
        filepath = os.path.join(settings.STATICFILES_DIRS[0],'images/logos/')

        filename = filepath + file.name
        with open(filename,'wb') as f:
            f.write(file.file.read())

        return Response({
            "code": "200",
            "msg": "上传成功",
            "file_path": "/static/images/logos/",
            "file_name": file.name
        }, status=200)


#加载所有的频道数据
from rest_framework.generics import ListAPIView
from .models import *
from .serializer import *
class ListChannelAPIView(ListAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer

#加载所有的商品类别
class ListCateAPIView(ListAPIView):
    queryset = Cate.objects.all()
    serializer_class = CateSer

#加载一个 更新一个 删除一个 频道组数据
from rest_framework.generics import RetrieveUpdateDestroyAPIView
class ChannelAPIView(RetrieveUpdateDestroyAPIView):
    queryset = Group.objects.all()
    serializer_class = GroupSer
    lookup_field = "pk"
    lookup_url_kwarg = 'pk'

#加载一级类别
class FirstCateAPIView(ListAPIView):
    queryset = Cate.objects.filter(cid=None)
    serializer_class = CateSer

#增加一个频道组---视图
from rest_framework.views import APIView
class AddChannelView(APIView):
    def post(self,request):
        name = request.data.get('name')
        cate_name = request.data.get('cate_name')
        group_url = request.data.get('url')
        sequence = request.data.get('sequence')
        #判断cate_name 这个类别是否存在
        cate = Cate.objects.filter(name=cate_name).first()
        if not cate:
            return Response({'code':"400",'msg':'添加类别不存在'})
        #组织数据
        data= {
            'name':name,
            'cate':cate.id,
            'group_url':group_url,
            'sequence':sequence
        }
        #实例化序列化器对象
        ser = GroupSer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({'code':'200','msg':'添加频道组成功','data':ser.data})

        else:
            return Response({'code':'400','msg':ser.error_messages})

#SKU视图
class SKUViewSet(ModelViewSet):
    queryset = SKU.objects.all()
    serializer_class = SKUSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

#SPU视图
class SPUViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SPUSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

#加载所有的子类别
class SubCateViewSet(ModelViewSet):
    queryset = Cate.objects.all()
    serializer_class = CateSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'
    def retrieve(self, request, pk,*args, **kwargs):
        #获取pk类别下的所有二级类别
        sub_cate = self.get_queryset().filter(cid=pk)
        #对子类别进行 序列化输出
        sub_cate_ser = self.get_serializer(sub_cate,many=True)
        return Response(sub_cate_ser.data)


#SPU规格的视图集
class SPUSpecificationViewSet(ModelViewSet):
    queryset = SPUSpecification.objects.all()
    serializer_class = SPUSpecificationSer
    lookup_field =  'pk'
    lookup_url_kwarg = 'pk'

    def create(self, request, *args, **kwargs):
        print(request.data)
        name = request.data.get("name")
        spu = request.data.get("spu")
        rust = SPUSpecification.objects.filter(name=name, spu=spu)
        if rust:

            return Response({"msg": '数据存在,不可重复添加'})
        else:
            SPUSpecification.objects.create(name=name, spu=spu)
            return Response({"msg": '添加成功', "code": '200'})


#规格选项值的视图集
class SpecificationOptionViewSet(ModelViewSet):
    queryset = SpecificationOption.objects.all()
    serializer_class = SpecificationOptionSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

#上传商品图片

class UploadSKUImageAPIView(APIView):
    def post(self,request):
        #获取文件
        file = request.data.get('file')
        #处理相关的路径
        file_name = file.name
        static_path = "static/images/goods"
        file_path = os.path.join(settings.BASE_DIR,static_path)
        #若目录不存在，则主动创建
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        #获取图片的绝对路径
        sku_image = os.path.join(file_path,file_name)
        #写入图片的字节流
        with open(sku_image,'wb') as f:
            f.write(file.file.read())

        return Response({
            'code':'200',
            'msg':'上传商品成功',
            'static_path':static_path
        })
#skuimage的视图集
class SKUImageViewSet(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = SKUImageSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'

    #重写create方法
    def create(self, request, *args, **kwargs):
        print("数据",request.data)
        #获取前端传入的数据
        sku_id = request.data.get('sku')
        image = request.data.get('image')
        #防止重复添加图片
        sku_image = SKUImage.objects.filter(sku_id=sku_id,images=image)
        if sku_image:
            return Response({'code':'400','msg':'当前商品已存在，无法重复添加！'})
        #正常存入数据库
        try:
            SKUImage.objects.create(sku_id=sku_id,images=image)
            return Response({'code':'200','msg':'添加图片成功'})
        except Exception as e:
            print("...",e.args)
            return Response({'code':'400','msg':'添加图片失败'})

    #重写list方法
    def list(self, request, *args, **kwargs):
        #获取所有的商品图片数据
        sku_images = self.get_queryset()
        #序列化
        sku_images_ser = self.get_serializer(sku_images,many=True)
        #处理序列化数据
        my_data = []
        for i in sku_images_ser.data:
            i['images'] = i.get('images').split("/goods/imgs")[1]
            my_data.append(i)
        return Response(my_data)

    #重写retrieve方法
    def retrieve(self, request,pk, *args, **kwargs):
        sku_image = self.get_queryset().filter(id=pk).first()
        sku_image_ser = self.get_serializer(sku_image)
        my_data = sku_image_ser.data
        my_data['images'] = os.path.join("/static",my_data.get('images').split('static/')[1])

        return Response(my_data)

    #重写update方法
    def update(self, request,pk, *args, **kwargs):
        sku_id = request.data.get('sku')
        image = request.data.get('images')
        sku_image = self.get_queryset().filter(id=pk).first()
        sku_image.sku_id = sku_id
        sku_image.images = image
        sku_image.save()
        return Response({'code':"200",'msg':'更新成功'})


